package com.blood.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blood.core.config.mybatisplus.ICommonServiceImpl;
import com.blood.core.constant.RedisKey;
import com.blood.core.enums.AuthorityTypeEnum;
import com.blood.core.enums.RoleTypeEnum;
import com.blood.core.enums.StatusEnum;
import com.blood.core.resp.GlobalResultStatus;
import com.blood.core.resp.ResponseResult;
import com.blood.core.util.ObjectAssertUtil;
import com.blood.core.util.bean.ListUtils;
import com.blood.core.util.http.RequestTheadUtils;
import com.blood.modules.system.dto.req.SysRoleAuthorityReq;
import com.blood.modules.system.dto.resp.SysRoleAuthorityInfoResp;
import com.blood.modules.system.dto.resp.SysRoleAuthorityListResp;
import com.blood.modules.system.mapper.SysRoleAuthorityMapper;
import com.blood.modules.system.model.SysRoleAuthority;
import com.blood.modules.system.model.SysUserRole;
import com.blood.modules.system.service.ISysOrgSchemaService;
import com.blood.modules.system.service.ISysRoleAuthorityService;
import com.blood.modules.system.service.ISysUserRoleService;
import com.blood.redis.config.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 角色权限Service业务层处理
 *
 * @author daoren
 * @date 2022-11-23 11:09:29
 */
@Service
public class SysRoleAuthorityServiceImpl extends ICommonServiceImpl<SysRoleAuthorityMapper, SysRoleAuthority> implements ISysRoleAuthorityService {

    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysOrgSchemaService sysOrgSchemaService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 启动添加角色登录权限
     */
    @PostConstruct
    public void init() {
        loadingCache();
    }

    public void loadingCache() {
        List<SysRoleAuthority> authorityList = baseMapper.selectList(new QueryWrapper<SysRoleAuthority>()
                .lambda()
                .eq(SysRoleAuthority::isDeleteFlag, false));
        for (SysRoleAuthority roleAuthority : authorityList) {
            redisUtil.set(RedisKey.ROLE_AUTH.concat(roleAuthority.getRoleId()).concat("-") + roleAuthority.getType(), roleAuthority.getStatus());
        }
    }


    @Override
    public ResponseResult<List<SysRoleAuthorityListResp>> queryList() {
        List<SysUserRole> roleList = sysUserRoleService.queryList();
        if (roleList.size() > 0) {
            ArrayList<SysRoleAuthorityListResp> respList = new ArrayList<>(roleList.size());
            List<SysRoleAuthority> authorityList = baseMapper.selectList(new QueryWrapper<SysRoleAuthority>()
                    .lambda()
                    .eq(SysRoleAuthority::isDeleteFlag, false)
                    .orderByAsc(SysRoleAuthority::getLineNo));
            for (SysUserRole sysUserRole : roleList) {
                SysRoleAuthorityListResp resp = new SysRoleAuthorityListResp();
                resp.setName(sysUserRole.getName());
                resp.setAuthorityList(ListUtils.copyProperties(authorityList.stream()
                        .filter(f -> sysUserRole.getId().equals(f.getRoleId()))
                        .collect(Collectors.toList()), SysRoleAuthorityInfoResp.class));
                respList.add(resp);
            }
            return GlobalResultStatus.SUCCESS.toResult().response(respList);
        }
        return GlobalResultStatus.SUCCESS.toResult().response(Collections.emptyList());
    }

    @Override
    public void queryDataAuthority(QueryWrapper queryWrapper) {
        if (!RoleTypeEnum.ADMIN.getValue().equals(RequestTheadUtils.getRole())) {
            Object all = redisUtil.get(RedisKey.ROLE_AUTH.concat(RequestTheadUtils.getRole()).concat("-") + AuthorityTypeEnum.ALL.getValue());
            if (null != all && StatusEnum.ENABLE.getValue().equals(all)) {
                return;
            }
            Object depart = redisUtil.get(RedisKey.ROLE_AUTH.concat(RequestTheadUtils.getRole()).concat("-") + AuthorityTypeEnum.DEPART.getValue());
            if (null != depart && StatusEnum.ENABLE.getValue().equals(depart)) {
                List<String> myOrSubList = sysOrgSchemaService.queryMyOrSubList(RequestTheadUtils.getHospitalId());
                queryWrapper.in("org_id", myOrSubList);
                return;
            }
            queryWrapper.eq("org_id", RequestTheadUtils.getDepartId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateInfo(SysRoleAuthorityReq req) {
        SysRoleAuthority queryInfo = super.findById(req.getId());
        ObjectAssertUtil.objectIsNull(queryInfo, "未获取到详细信息!");
        queryInfo.setStatus(req.getStatus());
        queryInfo.setUpdateBy(RequestTheadUtils.getUserId());
        redisUtil.set(RedisKey.ROLE_AUTH.concat(queryInfo.getRoleId()).concat("-") + queryInfo.getType(), queryInfo.getStatus());
        baseMapper.updateById(queryInfo);
    }


}
